﻿using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Dynamic;
using System.Threading;
using System.Web;
using U8;
using System.Collections.Generic;
using System.Linq;



namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class postBom : IHttpHandler
    {
        private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); // 最大并发数设为1

        public static readonly string bz = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;

        public void ProcessRequest(HttpContext context)
        {
            _semaphore.Wait(); // 请求资源
            string authHeader = HttpContext.Current.Request.Headers["Authorization"];
            string bearerToken = authHeader.Substring("Bearer ".Length).Trim();
            PetaPoco.Database dbw = new PetaPoco.Database(bz);

            XZ_RZBfaModel RZB = new XZ_RZBfaModel();
            
            RZB.类型 = "BOM";
            RZB.日期 = DateTime.Now;
            object jsonData = "";
            FileLogHelper.WriteTxtLog("调用开始", "11");
            dynamic jsonF = new ExpandoObject();  //动态MODEL 存DATE
            dynamic res = new ExpandoObject();  //动态MODEL 返回值
            res.msg = "";
            TokenModel model = dbw.FirstOrDefault<TokenModel>("select  * from  Token  where token=@token and  DATEDIFF(DAY,date, GETDATE())=0", new { token = bearerToken });
            if (model == null)
            {
                res.code = 401;
                res.msg = "密钥不合法或者已经过期";
                res.count = 0;
                jsonData = JsonConvert.SerializeObject(res);
                context.Response.Write(jsonData);
                _semaphore.Release(); // 释放资源

            }
            else
            {
                try
                {


                    byte[] postData = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(postData, 0, postData.Length);
                    string postDataString = System.Text.Encoding.UTF8.GetString(postData);
                    FileLogHelper.WriteTxtLog("调用开始", postDataString);


                    RZB.JSON = postDataString;
                    InventoryInfo U8fa = JsonConvert.DeserializeObject<InventoryInfo>(postDataString);

                 
                    
                    var hasDuplicates = U8fa.InventorySub.GroupBy(m => m.cInvCodeSub)
                                                    .Any(g => g.Count() > 1);

                    if (hasDuplicates)
                    {
                        res.msg = "BOM子机有重复";
                        res.code = 999;
                        RZB.是否成功 = "失败";
                        return;
                    }

                    U8fa.cmaker = model.name;
                    //根据母件和版本号找到对应的BOMID
                    InventoryInfo BOM = dbw.SingleOrDefault<InventoryInfo>("SELECT a.BomId,VersionEffDate  from bom_bom a,bom_parent b where a.BomId = b.BomId  and exists(select  1 from bas_part c where b.ParentId = c.PartId and invcode = '" + U8fa.cInvCode + "') and  Version = '" + U8fa.Version + "'");

                    //如果找不到BOMID，证明需要新增ID,这个时候获取该母件最大的BOM版本日期并且加1，作为新的BOM的版本日期，如果没有则取当前日期
                    if (BOM == null)
                    {
                        U8fa.VersionEffDate = dbw.SingleOrDefault<string>("SELECT    CASE WHEN   max(DATEADD(day, 1, VersionEffDate))>CONVERT(VARCHAR, GETDATE(), 23)  THEN  max(DATEADD(day, 1, VersionEffDate)) ELSE  CONVERT(VARCHAR, GETDATE(), 23) END  VersionEffDate  from bom_bom a,bom_parent b where a.BomId = b.BomId  and exists(select  1 from bas_part c where b.ParentId = c.PartId and invcode = '" + U8fa.cInvCode + "')  ");
                    }
                    else
                    {
                        U8fa.BomID = BOM.BomID;
                        U8fa.VersionEffDate = BOM.VersionEffDate;
                    }
                    //回传新增ID
                    long bomid = 0;
                    Inventory1 aa = new Inventory1();
                    res.msg = aa.Save(U8fa, ref bomid);




                    if (res.msg != "")
                    {
                        RZB.是否成功 = "Flase";
                        RZB.错误内容 = res.msg;


                        res.code = 999;
                        

                    }
                    else
                    {

                        RZB.是否成功 = "失败";
                        RZB.返回ID = bomid.ToString();


                        res.code = 200;
                        res.msg = "CO成功";
                        res.data = jsonData;
                       
                    }

                }

                catch (Exception ee)
                {
                    RZB.是否成功 = "失败";
                    RZB.错误内容 = ee.Message; ;

                    if (ee.Message.Length > 50)
                    {
                        res.msg = ee.Message.Substring(0, 50);
                    }
                    else
                    {
                        res.msg = ee.Message;
                    }
                    res.code = 999;
                    

                }
                finally
                {
                    dbw.Save(RZB);
                    jsonData = JsonConvert.SerializeObject(res);
                    context.Response.ContentType = "application/json";
                    context.Response.Write(jsonData);
                    _semaphore.Release(); // 释放资源

                }
               
            }


  
        }




        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string res(string ccode, string msg, string jsonData)
        {
            string resstr = "";


            return resstr;
        }


    }
}